package com.jwb.pub.serviceImpl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jwb.pub.dao.BaseDAO;
import com.jwb.pub.model.JavaModel;
import com.jwb.pub.service.RoleService;
import com.jwb.util.ToolsUtil;

@Service(value="roleService")

public class RoleServiceImpl implements RoleService {

	@Autowired
	private BaseDAO baseDAO;
	
	
	/**
	 * 获取所有用户权限列表
	 * 
	 * @author LIU CHANG
	 * 
	 * @param userId
	 * @param dataBaseDAO
	 * @return
	 * 
	 */
	@Override
	public JSONObject getRoleList(JSONObject jsdata){
		JSONObject jsobject = new JSONObject();
		String sql ="";
		String sqlWhere = null;
		if(jsdata.isEmpty()) {
			sqlWhere = "";
		}else{			
		}
		if(sqlWhere==null ||"".equals(sqlWhere)){ 
			sql="select role_id, role_name, '0' is_check from role order by role_id";			
		}else{  //a.userId = 'userId'
			sql="select b.role_id, b.role_name, instr(a.role_list, ','||b.role_id||',', 1)+1 is_check from user_info a, role b where "
					+ sqlWhere + " order by b.role_id";
		}
		
		try {
			JSONObject roleJson = new JSONObject();
			roleJson = baseDAO.findBySqlToJosn(sql);
			//is_check  0: false, 1: true
			JSONArray array =roleJson.getJSONArray("list");
			for(int i=0;i<array.size();i++){
				JSONObject obj = array.getJSONObject(i);
				int chk = Integer.valueOf((String)obj.get("is_check"));
				if(chk>1) obj.put("checked", "true");
				else obj.put("checked", "false");
			}
			//array.getJSONObject(index)
			System.out.println(roleJson);
			
			if(roleJson==null||roleJson.isEmpty()){
				jsobject.put("respCode", "1");
				jsobject.put("respDesc", "角色列表显示失败，请重试!");
			}else{
				jsobject.put("respCode", "0");
				jsobject.put("respDesc","角色列表显示成功!");
				jsobject.put("rolelist", roleJson);
			}
			
		} catch (Exception e) {
			jsobject.put("respCode", "9");
			jsobject.put("respDesc", "系统忙，请联系系统管理员!");
			e.printStackTrace();
		}
		
		
		return jsobject;
	}
	
	
	
	
	/**
	 * 
	 * @description：保存角色信息
	 * @author LIU CHANG
	 * @throws Exception 
	 * 
	 * 
	 * @createDate 2018-03-19
	 * @createTime 下午3:35:16
	 */	
	
	public JSONObject roleInfoSave(JSONObject jsdata){
		String roleName = jsdata.getString("roleName");
		JSONObject jsobject= new JSONObject();
		try{
			int roleCnt = getRoleCnt("",roleName);
			if(roleCnt>0){
				jsobject.put("respCode", "2");
				jsobject.put("respDesc", "角色已存在!");
			}
			else{
				String addSql = "insert into role(role_name) values(?)";
			    ArrayList<JavaModel> list = new ArrayList<JavaModel>();
			    list.add(new JavaModel(roleName));
			    if(baseDAO.excuteSql(addSql,list)){
			    	String sql="SELECT * FROM role Where role_name='"+roleName+"'";
					jsobject.put("roleJson", baseDAO.findBySqlToJosn(sql));
					jsobject.put("respCode", "0");
					jsobject.put("respDesc", "角色保存成功!");
			    }else{
			    	jsobject.put("respCode", "-1");
					jsobject.put("respDesc", "角色保存失败!");
			    }			
			}
		}catch(Exception e){
			jsobject.put("respCode", "9");
			jsobject.put("respDesc", "系统忙，请联系系统管理员!");
		}
		
		return jsobject;
	}
	
	
	public int getRoleCnt(String roleId,String roleName) throws Exception{
		String sql="";
		if(roleId==null||"".equals(roleId.trim())){
			sql=" SELECT COUNT(*) FROM role where role_name='"+roleName+"'";
		}else{
			sql = "SELECT COUNT(*) FROM role where role_name='"+roleName+"' and role_id<>'"+roleId+"'";
		}
		int roleCnt = baseDAO.findBySqlCnt(sql);
		System.out.println(roleCnt);
		return roleCnt; 
	}
	
	/**
	 * 角色权限对应关系维护
	 */
	public JSONObject roleEdit(JSONObject jsdata){
		String roleId = jsdata.getString("roleId");
		JSONObject jsobject = new JSONObject();
		JSONArray array = new JSONArray();
		String querySql = "select role_id, role_name, role_level, remarks, sys_name from role where role_id="+Integer.valueOf(roleId);
		try {
			JSONArray jsarray = baseDAO.findBySqlToJosn(querySql).getJSONArray("list");
			JSONObject jobj = jsarray.getJSONObject(0);
			jsobject.put("roleId", jobj.getString("role_id"));
			jsobject.put("roleName", jobj.getString("role_name"));
			jsobject.put("roleLevel", jobj.getString("role_level"));
			jsobject.put("remarks", jobj.getString("remarks"));
			jsobject.put("sysName", jobj.getString("sys_name"));
					
			String privSql = "select distinct priv_group, group_order from privilege order by group_order";
			JSONArray list = baseDAO.findBySqlToJosn(privSql).getJSONArray("list");
			if(list.size()>0){
				for(int i=0;i<list.size();i++){
					JSONObject jso = list.getJSONObject(i);
					String privGroup = jso.getString("priv_group");
					jso.put("privGroup", privGroup);
					jso.put("groupOrder", jso.getString("group_order"));
					JSONArray rolePrivList = getRolePrivList(roleId,privGroup).getJSONArray("rolePrivList");
					JSONArray  jsarryRp = new JSONArray();
					for(int j=0;j<rolePrivList.size();j++){
						JSONObject jsonRp = new JSONObject();
						jsonRp.put("privRemarks", rolePrivList.getJSONObject(j).get("remarks"));
						jsonRp.put("displayOrder", rolePrivList.getJSONObject(j).get("displayOrder"));
						jsonRp.put("privCode", rolePrivList.getJSONObject(j).get("privCode"));
						jsonRp.put("sprivCode", rolePrivList.getJSONObject(j).get("sprivCode"));
						jsarryRp.add(jsonRp);
					}
			    	jso.put("rolePrivList", jsarryRp); 
			    	array.add(jso);
				}
								
				
//			List<Object[]> list = baseDAO.findBySql(privSql);
//			if(!list.isEmpty()){
//				for(Object[] obj:list){
//					JSONObject jso = new JSONObject();
//					String privGroup = (obj[0]==null?"":(String)obj[0]);
//					jso.put("privGroup", privGroup);
//					jso.put("groupOrder", obj[1]==null?"":(String)obj[1]);
//					
//					JSONArray rolePrivList = roleService.getRolePrivList(roleId,privGroup).getJSONArray("rolePrivList");
//					JSONArray  jsarryRp = new JSONArray();	
//					for(int i=0;i<rolePrivList.size();i++){
//						JSONObject jsonRp = new JSONObject();
//						jsonRp.put("privRemarks", rolePrivList.getJSONObject(i).get("remarks"));
//						jsonRp.put("displayOrder", rolePrivList.getJSONObject(i).get("displayOrder"));
//						jsonRp.put("privCode", rolePrivList.getJSONObject(i).get("privCode"));
//						jsonRp.put("sprivCode", rolePrivList.getJSONObject(i).get("sprivCode"));
//						jsarryRp.add(jsonRp);
//					}
//			    	jso.put("rolePrivList", jsarryRp); 				
//					
//					array.add(jso);
//				}								
				
				String sql = " select priv_code,priv_name, remarks from privilege "+ 
							 " where priv_code in ( "+
							 " select priv_code from role_priv where role_id ="+Integer.valueOf(roleId)+" )";
				jsobject.put("privList", baseDAO.findBySqlToJosn(sql).getJSONArray("list"));
				jsobject.put("privGroupList", array);
				jsobject.put("respCode", "0");
			    jsobject.put("respDesc", "OK");
			}else{
				 jsobject.put("respCode", "-1");
			     jsobject.put("respDesc", "未找到数据");
			}

		} catch (Exception e) {
			e.printStackTrace();
			jsobject.put("respCode", "9");
		    jsobject.put("respDesc", "系统忙，请联系系统管理员!");
		    return jsobject;
		}				
		
		return jsobject;
	}
	
	/**
	 * 权限分组查询
	 * @description：
	 * @author 刘亚楠
	 *
	 * @param roleId
	 * @param privGroup
	 * @return
	 * @throws DBException
	 *
	 * @createDate 2015-1-19
	 * @createTime 下午4:04:28
	 */
	
	public JSONObject getRolePrivList(String roleId,String privGroup)
	{
		String strsql = "";
		JSONObject jsobject = new JSONObject();
		JSONArray array = new JSONArray();
		try
		{
			
			strsql = "select a.*, b.* from "
					+ " (select p.remarks, p.priv_group, p.display_order, p.group_order, p.priv_code "
					+ " from v_privilege p where p.priv_group='"+privGroup+"' order by p.priv_group) a left join (select p.priv_code s_priv_code "
					+ " from privilege p where p.priv_code in (select priv_code from role_priv t where t.role_id ='"
					+ roleId
					+ "') order by p.priv_group) b on a.priv_code = b.s_priv_code "
					+ " order by a.group_order, a.display_order";
			
			
			JSONArray list = baseDAO.findBySqlToJosn(strsql).getJSONArray("list");
			for(int i=0;i<list.size();i++){
				JSONObject jso = list.getJSONObject(i);
				jso.put("remarks", jso.getString("remarks"));
				jso.put("privGroup", jso.getString("priv_group"));
				jso.put("displayOrder", jso.getString("display_order"));
				jso.put("groupOrder", jso.getString("group_order"));
				jso.put("privCode", jso.getString("priv_code"));
				jso.put("sprivCode", jso.getString("s_priv_code"));
				array.add(jso);
			}
//			List<Object[]> list = baseDAO.findBySql(strsql);
//			
//			for (Object[] obj:list)
//			{
//				JSONObject jso = new JSONObject();
//				jso.put("remarks", obj[0]==null?"":obj[0]);
//				jso.put("privGroup", obj[1]==null?"":obj[1]);
//				jso.put("displayOrder", obj[2]==null?"":obj[2]);
//				jso.put("groupOrder", obj[3]==null?"":obj[3]);
//				jso.put("privCode", obj[4]==null?"":obj[4]);
//				jso.put("sprivCode", obj[5]==null?"":obj[5]);
//				array.add(jso);
//			}
			jsobject.put("rolePrivList", array);
			jsobject.put("respCode", "0");
			jsobject.put("respDesc", "OK");
			
			return jsobject;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "查询数据库失败");
			return null;
		}
		
	}
	
	public JSONObject getPrivCodes(JSONObject jsdata){
		JSONObject jsobject = new JSONObject();
		String privList = jsdata.getString("privList");
		String sql = "select priv_code,remarks from privilege where remarks in ("+privList+")";
		StringBuffer privCodes = new StringBuffer("");
		try {
			JSONArray list = baseDAO.findBySqlToJosn(sql).getJSONArray("list");
			for(int i=0;i<list.size();i++){
				privCodes.append(list.getJSONObject(i).getString("priv_code"));
				if(i<list.size()-1)
				privCodes.append(",");
			}
//			List<Object[]> list = baseDAO.findBySql(sql);
//			for(Object[] obj:list){
//				privCodes.append((String)obj[0]);
//				privCodes.append(",");
//			}
			jsobject.put("privCodes", privCodes.toString());
			jsobject.put("respCode", "0");
			jsobject.put("respDesc", "OK");
		} catch (Exception e) {
			jsobject.put("privCodes", privCodes.toString());
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "查找失败");
		}		
		return jsobject;
	}
	
	/**
	 * 保存角色权限关系
	 * @description：
	 * @author LIU CHANG
	 *
	 * @param role
	 * @param privs
	 * @return
	 *
	 * @createDate 2018-3-19
	 * @createTime 下午3:47:20
	 */
	
	public JSONObject rolePrivSave(JSONObject jsdata){
		String roleId = jsdata.getString("roleId");
		String roleName = jsdata.getString("roleName");
		String[] privs = jsdata.getString("privCodes").split(",");
		JSONObject jsobject = new JSONObject();
		try
		{   
			if("".equals(roleId)){
//				roleId = ToolsUtil.get32bituuid();
				String addSql="INSERT INTO role (role_name) VALUES(?)";
				ArrayList<JavaModel> list = new ArrayList<>();
				list.add(new JavaModel(roleName));
				if(!baseDAO.excuteSql(addSql, list)){
					jsobject.put("respCode", "-1");
					jsobject.put("respDesc", "保存角色失败");
				}
				String sql = "SELECT role_id FROM role where role_name='"+roleName+"' ";
				JSONObject json = baseDAO.findBySqlToJosn(sql).getJSONArray("list").getJSONObject(0);
				roleId = String.valueOf(json.getInteger("role_id"));
			}else{
				String updateSql="Update role SET role_name=? Where role_id=?";
				ArrayList<JavaModel> list = new ArrayList<>();
				list.add(new JavaModel(roleName));
				list.add(new JavaModel(Integer.valueOf(roleId)));
				if(!baseDAO.excuteSql(updateSql,list)){
					jsobject.put("respCode", "-1");
					jsobject.put("respDesc", "保存角色失败");
				}				
			}
			
			String sqlStr="delete from role_priv where role_id = ? " ;
			ArrayList<JavaModel> list = new ArrayList<>();
			list.add(new JavaModel(Integer.valueOf(roleId)));
			baseDAO.excuteSql(sqlStr,list);
			
		    for (int i = 0; i < privs.length; i++)
			{
		    	if(!"".equals(privs[i]))
		    	{
		    		int privCode = Integer.valueOf(privs[i]);
		    		String addSql="INSERT INTO role_priv(role_id,priv_code) VALUES(?,?)";
		    		list = new ArrayList<>();
		    		list.add(new JavaModel(Integer.valueOf(roleId)));
		    		list.add(new JavaModel(privCode));
		    		baseDAO.excuteSql(addSql,list);
		    	}
			} 
		    
		    jsobject.put("roleId", roleId);
			jsobject.put("roleName", roleName);
		    jsobject.put("respCode", "0");
		    jsobject.put("respDesc", "OK");
		    return  jsobject;
		}catch(Exception e){
			jsobject.put("respCode", "9");
			jsobject.put("respDesc", "保存角色权限关系失败");
		}
		
		
	    return jsobject;
	}
	
	
	/**
	 * 删除角色权限信息
	 * 
	 * @author LIU CHANG
	 * 
	 * @param roleId
	 * @param dataBaseDAO
	 * 
	 */
	
	public JSONObject roleDelete(JSONObject jsdata){ 
		JSONObject jsobject = new JSONObject();
		int roleId = Integer.valueOf(jsdata.getString("roleId"));
		String sql = "SELECT count(*) FROM User_Info where instr(role_list,'"+roleId+"')>0 and sts='A'";
		try {
			int cnt = baseDAO.findBySqlCnt(sql);
			if(cnt>0){
				jsobject.put("respCode", "2");
				jsobject.put("respDesc", "该角色被分配中，不能删除!");
			}else{
				sql="delete from role_priv where role_id=?";
				ArrayList<JavaModel> list = new ArrayList<>();
				list.add(new JavaModel(roleId));
				if(!baseDAO.excuteSql(sql, list)){
					jsobject.put("respCode", "-1");
					jsobject.put("respDesc", "角色权限信息删除失败！");
					return jsobject;
				}
				sql="delete from role where role_id=?";
				if(!baseDAO.excuteSql(sql,list)){
					jsobject.put("respCode", "-1");
					jsobject.put("respDesc", "角色信息删除失败！");
					return jsobject;
				}
				jsobject.put("respCode", "0");
				jsobject.put("respDesc", "角色删除成功！");
				jsobject.put("roleId", roleId);
			}			
			
		} catch (Exception e) {
			jsobject.put("respCode", "9");
			jsobject.put("respDesc", "系统忙，请联系系统管理员!");
		}
		
		return jsobject;
	}
	
	
	
	
}
